package cn.tworice.mybatis.vo;


import cn.tworice.mybatis.po.SortingField;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@Schema(description="分页参数")
public class PageParam implements Serializable {
    @Schema(description = "页码，从 1 开始", example = "1")
    @NotNull(message = "页码不能为空")
    @Min(value = 1, message = "页码最小值为 1")
    private Integer page = 1;

    @Schema(description = "每页条数，最大值为 100", example = "10")
    @NotNull(message = "每页条数不能为空")
    @Min(value = 1, message = "每页条数最小值为 1")
    @Max(value = 100, message = "每页条数最大值为 100")
    private Integer pageSize = 10;

    public static <T> Page<T> buildPage(PageParam pageParam) {
        List<SortingField> list = new ArrayList<>();
//        list.add(new SortingField("create_time", SortingField.ORDER_DESC));
        return buildPage(pageParam, list);
    }

    public static <T> Page<T> buildPage(PageParam pageParam, Collection<SortingField> sortingFields) {
        // 页码 + 数量
        Page<T> page = new Page<>(pageParam.getPage(), pageParam.getPageSize());
        // 排序字段
        if (sortingFields!=null && !sortingFields.isEmpty()) {
            page.addOrder(sortingFields.stream().map(
                    sortingField -> SortingField.ORDER_ASC.equals(sortingField.getOrder()) ?
                            OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField())
                    )
                    .collect(Collectors.toList()));
        }
        return page;
    }
}
